﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OhioState.Tiling;
using UnityEngine;

namespace OhioState.Tiling
{
    public class PerlinTerrain : MonoBehaviour
    {
        public int noiseResolution;
        public int textureResolution;
        public int width;
        public int height;
        public float tileWidth;
        public float tileHeight;
        public int horizontalColors;
        public int verticalColors;
        public Terrain tileTerrain;
        void Start()
        {
            PerlinNoiseEdgeColorBuilder edgeColorBuilder = new PerlinNoiseEdgeColorBuilder(noiseResolution);
            PerlinNoiseTileSetBuilder builder = new PerlinNoiseTileSetBuilder(horizontalColors, verticalColors, noiseResolution, edgeColorBuilder);
            tileSet = (PerlinNoiseTileSet)builder.Build();

            PerlinNoiseTilingBuilder tilingBuilder = new PerlinNoiseTilingBuilder(width, height, tileSet);
            GridTiling<Texture2D> tiling = (GridTiling<Texture2D>)tilingBuilder.BuildTiling();


            float[,] terrainHeights = new float[width*textureResolution,height*textureResolution];
            for (int y = 0; y < height; y++)
            {
                for (int x = 0; x < width; x++)
                {
                    PerlinNoiseTile tile = (PerlinNoiseTile)tiling.GetTile(y * width + x);
                    tile.TileData.Apply();
                    RenderTerrainTile(tile,x,y, terrainHeights);
                    tile.Print();
                   
                }
            }
            tileTerrain.terrainData.heightmapResolution = width * textureResolution;
            tileTerrain.terrainData.SetHeights(0, 0, terrainHeights);
            tileTerrain.terrainData.size = new Vector3(width*tileWidth, 6, height*tileHeight);

            Camera.main.transform.position = new Vector3(width * tileWidth * 0.5f, height * tileHeight , height * tileHeight * 0.5f);
            Camera.main.transform.rotation = Quaternion.identity;
            Camera.main.transform.rotation = Quaternion.Euler(90.0f, 0.0f, 0.0f);

        }
        void Update()
        {

        }

        void RenderTerrainTile(PerlinNoiseTile tile, int x, int y,  float[,] heights)
        {
            PerlinTileConstructionCPU construction = new PerlinTileConstructionCPU(tile);
            float[,] texture = construction.GetConstructedNoiseTile(textureResolution, textureResolution);



            for (int i = 0; i < textureResolution; i++)
            {

                for (int j = 0; j < textureResolution; j++)
                {
                    heights[(height -1 -x)*textureResolution +i, (width - 1 -y)*textureResolution + j] = 0.1f*(texture[i,j] * 0.5f + 0.5f);    
                }
               
            }
            
          
            
        }
        
        private PerlinNoiseTileSet tileSet;
    }
}
